import React from 'react';
import {View} from 'react-native';
import {
  useSetState,
  useSafeState,
  useMount,
  useUnmount,
  useDebounceEffect,
} from 'ahooks';
import dayjs from 'dayjs';
import {ThemeProvider, createTheme} from '@rneui/themed';
import {
  SafeAreaProvider,
  useSafeAreaInsets,
} from 'react-native-safe-area-context';
import {Provider as ReduxProvider, useSelector, useDispatch} from 'react-redux';
import getStore, {setSafeAreaData} from './store';

import {
  localMongoDbFileSystem,
  localMongoDbAppConfig,
} from './LocalMongoDbInit';

import GlobalContext from '@/GlobalContext';
import InitData from './InitData';
import AppStateChange from './AppStateChange';
import Nav from './Nav';

const theme = createTheme({
  // lightColors: {
  //   primary: '#e7e7e8',
  // },
  // darkColors: {
  //   primary: '#000',
  // },
  // mode: 'light',
});

import EventEmitter from 'eventemitter3';
const eventEmitterGlobal = new EventEmitter();

export default () => {
  const [globalContext, setGC] = useSetState({
    navigation: undefined, //导航
  });
  const setGlobalContext = async (params = {}) => {
    for (const [key, value] of Object.entries(params)) {
      if (key !== 'setGlobalContext') {
        setGC({[key]: value});
      }
    }
  };
  const [store] = useSafeState(() => getStore());

  useMount(() => {
    console.log('Entry.jsx', 'useMount', dayjs().format());
  });
  useUnmount(() => {
    console.log('Entry.jsx', 'useUnmount', dayjs().format());
  });

  return (
    <GlobalContext.Provider
      value={{
        ...globalContext,
        setGlobalContext,
        localMongoDbFileSystem,
        localMongoDbAppConfig,
        eventEmitterGlobal,
      }}>
      <ReduxProvider store={store}>
        <ThemeProvider theme={theme}>
          <SafeAreaProvider>
            <InitData>
              <SafePadding>
                <AppStateChange>
                  <Nav />
                </AppStateChange>
              </SafePadding>
            </InitData>
          </SafeAreaProvider>
        </ThemeProvider>
      </ReduxProvider>
    </GlobalContext.Provider>
  );
};

const SafePadding = ({children}) => {
  const {left, right, top, bottom} = useSafeAreaInsets();
  const dispatch = useDispatch();
  const pageBackgroundColor = useSelector(
    state => state.pageBackgroundColor.value,
  );
  useDebounceEffect(() => {
    dispatch(
      setSafeAreaData({
        left,
        right,
        top,
        bottom,
      }),
    );
  }, [left, right, top, bottom]);
  return (
    <View
      style={{
        paddingTop: top,
        paddingRight: right,
        paddingBottom: bottom,
        paddingLeft: left,
        flex: 1,
        backgroundColor: pageBackgroundColor,
      }}>
      {children}
    </View>
  );
};
